package repository.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import repository.AuctionRepository;
import domain.Auction;
import domain.Item;


@Repository
public class AuctionRepositoryImpl extends AbstractHibernateRepository<Auction> implements AuctionRepository {
	
	@Autowired
	public AuctionRepositoryImpl(SessionFactory sessionFactory) {
		super(sessionFactory);
	}

	public void newAuction(Auction auction) {
		save(auction);
	}

	public Auction getAuction(int id) {
		return get(Auction.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public Auction getAuction(Item item) {
		if(item.getType().equals(Item.Type.auction)){
			String hql = "FROM Auction WHERE item=?";
			//TODO: USAR FIND!!! q si no nos ponen * por no usar Domain-Driven Design
			Session session = getSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, item);
			List<Auction> result = query.list();
			return result.size() > 0 ? result.get(0) : null;
		}
		return null;
	}
	
}
